const isDev = false;
const H5Host = isDev ? 'https://zlyx-shop.feekr.com' : 'https://youxuan.tourzj.com';
const apiHost = isDev ? 'https://zlyx-api.feekr.com' : 'https://zlyx-api.tourzj.com';
const webviewPath = '/pages/web/web?url=';
const orderList = '/pages/order/order';
Page({
  data: {
    paySuccessPath: '',
    payFailPath: `${H5Host}/order/confirm?isPayFailed=1`,
  },
  onLoad(param) {
    const { order_id } = param;
    this.useNativePath = param.payFail === 'order';
    if (!order_id) {
      wx.navigateBack();
      return;
    }
    this.submitData = {
      code: '',
      order_id,
      order_from: 'TOURZJ',
      shopid: 'ZLYX'
    }
    this.paySign = {};
    this.data.paySuccessPath = `${H5Host}/pay/success?id=${order_id}`;
    this.autoPay();
  },
  autoPay() {
    wx.showLoading({ title: '支付中...' })
    new Promise((resolve, reject) => {
      wx.login({
        success: ({ code }) => {
          if (!code) {
            reject('获取openid失败');
          }
          this.submitData.code = code;
          resolve();
        },
        fail() {
          reject('接口状态异常');
        }
      })
    })
      .then(this.getPaySign)
      .then(this.invokePay)
      .catch(err => {
        console.log(err);
      })
  },
  getPaySign() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${apiHost}/shop/wx_wap/tenpay`,
        method: 'POST',
        data: this.submitData,
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: ({ data: { result, status } }) => {
          if (!result.timeStamp || (status || {}).code !== 200) {
            reject('获取支付签名失败');
            status.message && wx.showModal({
              content: status.message,
              showCancel: false
            });
            return;
          }
          this.paySign = result;
          resolve();
        },
        fail() {
          reject('接口状态异常');
        },
        complete() {
          wx.hideLoading();
        }
      })
    })
  },
  invokePay() {
    wx.requestPayment({
      ...this.paySign,
      success: () => {
        wx.redirectTo({
          url: `${webviewPath}${encodeURIComponent(this.data.paySuccessPath)}`
        })
      },
      fail: () => {
        wx.redirectTo({
          //url: this.useNativePath ? orderList : `${webviewPath}${encodeURIComponent(this.data.payFailPath)}`
          url: orderList
        })
      }
    })
  }
})
